package com.py.credit.service.impl;

import com.py.credit.common.Page;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.dao.DataCompareDao;
import com.py.credit.entity.DataCompare;
import com.py.credit.service.DataCompareService;
import com.py.credit.utils.FileUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class DataCompareServiceImpl implements DataCompareService {

    @Autowired
    private DataCompareDao dataCompareDao;

    @Override
    public RestServiceResult doUploadFile(String jclb, MultipartFile file) {
        // TODO Auto-generated method stub
        // 获取文件的后缀
        String fileType = null;
        if (file != null) {
            // 获取文件后缀
            if (file.getOriginalFilename().contains(".")) {
                fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),
                        file.getOriginalFilename().length());
            }
        } else {
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "上传的文件不得为空");
        }
        if (!".xls".equalsIgnoreCase(fileType) && !".xlsx".equalsIgnoreCase(fileType)) {
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "上传的文件格式不支持");
        }

        Workbook wb = null;

        try {
            if (".xls".equalsIgnoreCase(fileType)) {
                wb = new HSSFWorkbook(file.getInputStream());
            } else if (".xlsx".equalsIgnoreCase(fileType)) {
                wb = new XSSFWorkbook(file.getInputStream());
            } else {
                return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "上传的文件格式不支持");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return readExcelValue(jclb, wb);
    }

    private RestServiceResult readExcelValue(String jclb, Workbook wb) {
        List<DataCompare> dataCompareList = new ArrayList<DataCompare>();
        //读取法人数据
        Sheet sheet = wb.getSheetAt(0);
        int rowNum = sheet.getLastRowNum();
        Row row;
        for (int j = 3; j <= rowNum; j++) {
            row = sheet.getRow(j);
            if (row == null) {
                continue;
            }
            DataCompare dc = new DataCompare();

            String name = getCellFormatValue(row.getCell(0));
            String tyshxydm = getCellFormatValue(row.getCell(1));
            String zzjgdm = getCellFormatValue(row.getCell(2));
            String gsdjm = getCellFormatValue(row.getCell(3));

            if (name.equals("")) {
                continue;
            }

            List<DataCompare> dcs = dataCompareDao.selectForFrList(jclb, name, tyshxydm, zzjgdm, gsdjm);
            for (DataCompare dataCompare : dcs) {
                dc = dataCompare;
                if (dc != null) {
                    dataCompareList.add(dc);
                }
            }
        }

        //读取自然人数据
        Sheet sheet1 = wb.getSheetAt(1);
        int rowNum1 = sheet1.getLastRowNum();
        Row row1;
        for (int j = 3; j <= rowNum1; j++) {
            row1 = sheet1.getRow(j);
            if (row1 == null) {
                continue;
            }
            DataCompare dc1 = new DataCompare();

            String name = getCellFormatValue(row1.getCell(0));
            String idcard = getCellFormatValue(row1.getCell(1));

            if (idcard.equals("")) {
                continue;
            }

            List<DataCompare> dc1s = dataCompareDao.selectForZrrList(jclb, name, idcard);
            for (DataCompare dataCompare : dc1s) {
                dc1 = dataCompare;
                if (dc1 != null) {
                    dataCompareList.add(dc1);
                }
            }
        }

        return new RestServiceResult(dataCompareList);
    }

    private String getCellFormatValue(Cell cell) {
        String cellvalue = "";
        if (cell != null) {
            // 判断当前Cell的Type
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC: // 如果当前Cell的Type为NUMERIC
                case Cell.CELL_TYPE_FORMULA: {
                    // 判断当前的cell是否为Date
                    if (DateUtil.isCellDateFormatted(cell)) {
                        // 如果是Date类型则，转化为Data格式
                        // data格式是带时分秒的：2013-7-10 0:00:00
                        // cellvalue = cell.getDateCellValue().toLocaleString();
                        // data格式是不带带时分秒的：2013-7-10
                        Date date = cell.getDateCellValue();
                        cellvalue = date.toLocaleString();
                    } else {// 如果是纯数字
                        // 取得当前Cell的数值
                        cellvalue = String.valueOf((int) cell.getNumericCellValue());
                    }
                    break;
                }
                case Cell.CELL_TYPE_STRING:// 如果当前Cell的Type为STRING
                    // 取得当前的Cell字符串
                    cellvalue = cell.getRichStringCellValue().getString();
                    break;
                default:// 默认的Cell值
                    cellvalue = "";
            }
        } else {
            cellvalue = "";
        }
        return cellvalue;
    }

    @Override
    public void downloadFilemb(String jclb, HttpServletResponse response) {
        String logPath = "";
        if (jclb.equals("C")) {
            logPath = DataCompareServiceImpl.class.getClassLoader().getResource("mb/cjcpmb.rar").getPath();
        } else {
            logPath = DataCompareServiceImpl.class.getClassLoader().getResource("mb/jlcpmb.rar").getPath();
        }

        FileUtil.downloadFile(logPath, response);
    }

    @Override
    public List<DataCompare> getCrossListForPage(Page page,String jclb) {
        if(jclb.equals("C")){
            return dataCompareDao.getCrossListForPage(page,jclb,"J");
        }else{
            return dataCompareDao.getCrossListForPage(page,jclb,"C");
        }
    }

    @Override
    public List<DataCompare> selectCrossDetailForPage(Page page, String type, String searchKey) {
        if(type.equals("C")){
            return dataCompareDao.selectCrossDetailForPage(page, type, searchKey,null);
        }else{
            return dataCompareDao.selectCrossDetailForPage(page, type, null,searchKey);
        }
    }
}
